package com.hw.pusher_example;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;

import com.hw.pusher.AppManager;
import com.hw.pusher.HWPushActivity;
import com.hw.pusher.push.PushData;
import com.hw.pusher.push.mi.MiProcessCheck;
import com.hw.pusher.utils.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import io.flutter.embedding.android.FlutterActivity;

import static com.hw.pusher.HWPushActivity.BRAND_HUAWEI;

public class DeepLinkActivity extends FlutterActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        decode();
    }

    void decode() {
        Intent intent = getIntent();
        if (null != intent && null != intent.getData()) {
            String name2 = intent.getStringExtra("name");
            if (!TextUtils.isEmpty(name2)) {
                Logger.d("get params from deepLink===================>" + name2);
                if (AppManager.getAppManager().hasActivity(MainActivity.class)) {
                    MiProcessCheck.setTopApp(this);
                    passMessage("", decode2Json(name2), 1);
                } else {
                    Intent launchIntent = new Intent(this, MainActivity.class);
                    launchIntent.putExtra(HWPushActivity._data, decode2Json(name2));
                    launchIntent.putExtra(HWPushActivity._type, BRAND_HUAWEI);
                    startActivity(launchIntent);
                }
            }
        }
        AppManager.getAppManager().finishActivity(this);
    }

    private String decode2Json(String json) {
        String res = json;
        try {
            json = URLDecoder.decode(json, "utf-8");
            return URLDecoder.decode(new String(com.huawei.hms.support.log.common.Base64.decode(json)), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return res;
    }

    private void passMessage(String token, String data, int action) {
        PushData pushData = new PushData();
        pushData.setType(HWPushActivity.BRAND_HUAWEI);
        pushData.setToken(token);
        pushData.setAction(action);
        pushData.setMessage(data);
        HWPushActivity.handler.postDelayed(() -> HWPushActivity.handler.sendMessage(HWPushActivity.createMessage(pushData)), 1 * 1000);
    }
}
